<?php

namespace app\admin\logic;

use support\Exception\ApiException;
use support\Service\MenuService;

class MenuLogic extends BaseLogic
{

    public function __construct()
    {
        self::$service = new MenuService();
    }

    protected static $checked_config = [
        'index' => '查询',
        'add' => '添加',
        'edit' => '修改',
        'delete' => '删除',
        'info' => '详情',
        'status' => '状态',
        'dall' => '批量删除',
        'addz' => '添加子级',
        'expand' => '全部展开',
        'collapse' => '全部折叠',
        'export' => '导出数据',
        'import' => '导入数据',
        'permission' => '分配权限',
        'resetpass' => '重置密码',
    ];

    /**
     * 菜单列表
     * @return array
     * @author 白鹄
     * @since 2024/01/01
     */
    public static function getList()
    {
        // 请求参数
        $param = request()->get();
        $where[] = ['mark', '=', 1];
        //菜单标题
        if (isset($param['title']) && $param['title']) {
            $where[] = ["title", 'like', "%{$param['title']}%"];
        }
        $list = self::$service::getList($where, ['*'], ['sort' => 'asc']);
        return message($list);
    }

    public static function getInfo()
    {
        $param = request()->get();
        if (!isset($param['id']) || empty($param['id'])) return message();
        $id = $param['id'];
        $where[] = ['mark', '=', 1];
        $where[] = ['id', '=', $id];
        $info = self::$service::getInfoByWhere($where);
        $checkedList = [];
        if ($info['type'] == 0) {
            $permissionList = self::$service::getList([["pid", "=", $info['id']], ["type", "=", 1], ["mark", "=", 1]], ['permission']);
            if (is_array($permissionList)) {
                foreach ($permissionList as $v) {
                    $permission = explode(":", $v['permission']);
                    $checkedList[] = $permission[count($permission) - 1];
                }
            }
            $info['checkedList'] = $checkedList;
        }
        return message($info);
    }

    /**
     * 获取权限列表
     * @param $userId 用户ID
     * @return mixed
     * @since 2020/11/19
     */
    public static function getPermissionList($userId)
    {
        $list = [];
        new self();
        if ($userId == 1) {
            // 管理员拥有全部权限
            $list = self::$service::getChilds(0);
        } else {
            // 其他角色
            $list = self::$service::getPermissionMenu($userId, 0);
        }
        return message($list);
    }

    public static function edit()
    {
        $data = request()->post();
        $id = $data['id'] ?? 0;
        if (!isset($data['title']) || empty($data['title'])) {
            throw new ApiException('请输入菜单名称');
        }
        if (!isset($data['sort']) || empty($data['sort'])) {
            throw new ApiException('请输入排序');
        }
        $save['title'] = trim($data['title']);
        $save['sort'] = $data['sort'];
        $save['component'] = $data['component'] ?? '';
        $save['hide'] = $data['hide'] ?? 0;
        $save['icon'] = $data['icon'] ?? '';
        $save['pid'] = $data['pid'] ?? 0;
        $save['path'] = $data['path'] ?? '';
        $save['status'] = $data['status'] ?? 1;
        $save['target'] = $data['target'] ?? '_self';
        $save['type'] = $data['type'] ?? 0;
        $save['permission'] = $data['permission'] ?? '';
        unset($data['id']);
        if ($id == 0) {
            $res = self::$service::add($save);
        } else {
            self::$service::save($save, $id);
            $res = $id;
        }
        if (!$res) {
            throw new ApiException('操作失败');
        }
        $checkedList = $data['checkedList'] ?? [];
        if ($data['type'] == 0 && !empty($data['path']) && !empty($checkedList)) {
            $path = explode("/", $data['path']);
            // 模块名称
            $moduleName = $path[count($path) - 1];
            foreach ($checkedList as $item) {
                if (!in_array($item, array_keys(self::$checked_config))) continue;


                $rule_data = [];
                $rule_data['pid'] = $res;
                $rule_data['type'] = 1;
                $rule_data['sort'] = 1;
                $rule_data['target'] = '_self';
                $rule_data['title'] = self::$checked_config[$item];
                $rule_data['permission'] = "sys:{$moduleName}:" . $item;
                // 判断当前节点是否已存在
                $permission_info = self::$service::getInfoByWhere([
                    ['pid', '=', $res],
                    ['type', '=', 1],
                    ['mark', '=', 1],
                    ['permission', '=', $rule_data['permission']],
                ]);
                if ($permission_info) continue;

                self::$service::add($rule_data);
            }

        }
        return message();

    }


}
